import { useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { 
  Target, 
  Users, 
  Lightbulb, 
  Wrench, 
  BookOpen, 
  Building, 
  Edit3,
  TrendingUp,
  MapPin,
  Star,
  ChevronRight
} from "lucide-react";
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart";
import { RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis, Radar, ResponsiveContainer } from "recharts";

interface RiasecCategory {
  code: string;
  name: string;
  description: string;
  score: number;
  icon: React.ReactNode;
  color: string;
  careers: string[];
  learningResources: string[];
}

const riasecData: RiasecCategory[] = [
  {
    code: "R",
    name: "Realistic",
    description: "Hands-on problem solvers who enjoy working with tools, machines, and physical materials",
    score: 65,
    icon: <Wrench className="w-5 h-5" />,
    color: "#22c55e",
    careers: ["Engineer", "Mechanic", "Architect", "Pilot", "Chef"],
    learningResources: ["Engineering Fundamentals", "Technical Skills Workshops", "Hands-on Projects"]
  },
  {
    code: "I",
    name: "Investigative",
    description: "Analytical thinkers who enjoy research, problem-solving, and working with ideas",
    score: 85,
    icon: <Target className="w-5 h-5" />,
    color: "#3b82f6",
    careers: ["Researcher", "Data Scientist", "Doctor", "Psychologist", "Analyst"],
    learningResources: ["Research Methods", "Data Analysis", "Scientific Literature"]
  },
  {
    code: "A",
    name: "Artistic",
    description: "Creative individuals who enjoy self-expression through various forms of art",
    score: 70,
    icon: <Lightbulb className="w-5 h-5" />,
    color: "#8b5cf6",
    careers: ["Designer", "Writer", "Musician", "Artist", "Film Director"],
    learningResources: ["Creative Writing", "Design Thinking", "Art History"]
  },
  {
    code: "S",
    name: "Social",
    description: "People-oriented individuals who enjoy helping, teaching, and working with others",
    score: 90,
    icon: <Users className="w-5 h-5" />,
    color: "#f59e0b",
    careers: ["Teacher", "Counselor", "Social Worker", "Nurse", "HR Manager"],
    learningResources: ["Communication Skills", "Psychology", "Leadership Development"]
  },
  {
    code: "E",
    name: "Enterprising",
    description: "Persuasive leaders who enjoy managing projects and influencing others",
    score: 55,
    icon: <TrendingUp className="w-5 h-5" />,
    color: "#ef4444",
    careers: ["CEO", "Sales Manager", "Entrepreneur", "Marketing Director", "Lawyer"],
    learningResources: ["Business Strategy", "Leadership Skills", "Marketing Fundamentals"]
  },
  {
    code: "C",
    name: "Conventional",
    description: "Detail-oriented individuals who enjoy organizing, planning, and working with data",
    score: 60,
    icon: <Building className="w-5 h-5" />,
    color: "#06b6d4",
    careers: ["Accountant", "Project Manager", "Administrator", "Librarian", "Financial Analyst"],
    learningResources: ["Project Management", "Data Organization", "Financial Planning"]
  }
];

const chartConfig = {
  score: {
    label: "Interest Level",
    color: "hsl(var(--primary))",
  },
};

export function InterestExplorer() {
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [isEditing, setIsEditing] = useState(false);

  const topCategories = riasecData.sort((a, b) => b.score - a.score).slice(0, 3);
  const selectedCategoryData = selectedCategory ? riasecData.find(cat => cat.code === selectedCategory) : null;

  const radarChartData = riasecData.map(cat => ({
    category: cat.code,
    score: cat.score,
    fullMark: 100
  }));

  const getRecommendedCareers = () => {
    return topCategories.flatMap(cat => 
      cat.careers.slice(0, 2).map(career => ({
        career,
        category: cat.name,
        match: cat.score,
        color: cat.color
      }))
    );
  };

  const getRecommendedResources = () => {
    return topCategories.flatMap(cat => 
      cat.learningResources.slice(0, 2).map(resource => ({
        resource,
        category: cat.name,
        relevance: cat.score,
        color: cat.color
      }))
    );
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="flex items-center gap-2">
                <MapPin className="w-5 h-5 text-primary" />
                Interest Explorer
              </CardTitle>
              <CardDescription className="mt-2">
                Discover your interests based on the RIASEC model and explore aligned career paths and learning opportunities.
                Your interests shape your career satisfaction and learning preferences.
              </CardDescription>
            </div>
            <Button variant="outline" size="sm" onClick={() => setIsEditing(!isEditing)}>
              <Edit3 className="w-4 h-4 mr-2" />
              {isEditing ? 'Save' : 'Edit Preferences'}
            </Button>
          </div>
        </CardHeader>
      </Card>

      <Tabs defaultValue="overview" className="space-y-4">
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="overview">Overview</TabsTrigger>
          <TabsTrigger value="categories">Interest Categories</TabsTrigger>
          <TabsTrigger value="careers">Career Matches</TabsTrigger>
          <TabsTrigger value="resources">Learning Resources</TabsTrigger>
        </TabsList>

        <TabsContent value="overview" className="space-y-4">
          <div className="grid md:grid-cols-2 gap-6">
            {/* RIASEC Radar Chart */}
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">Interest Profile</CardTitle>
                <CardDescription>Your RIASEC interest distribution</CardDescription>
              </CardHeader>
              <CardContent className="pb-6">
                <div className="w-full h-[250px]">
                  <ChartContainer config={chartConfig} className="w-full h-full">
                    <ResponsiveContainer width="100%" height="100%">
                      <RadarChart data={radarChartData} margin={{ top: 20, right: 30, bottom: 20, left: 30 }}>
                        <PolarGrid />
                        <PolarAngleAxis dataKey="category" className="text-xs" />
                        <PolarRadiusAxis angle={90} domain={[0, 100]} tick={false} />
                        <Radar
                          name="Interest Level"
                          dataKey="score"
                          stroke="hsl(var(--primary))"
                          fill="hsl(var(--primary))"
                          fillOpacity={0.3}
                          strokeWidth={2}
                        />
                        <ChartTooltip content={<ChartTooltipContent />} />
                      </RadarChart>
                    </ResponsiveContainer>
                  </ChartContainer>
                </div>
              </CardContent>
            </Card>

            {/* Top Interests */}
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">Your Top Interests</CardTitle>
                <CardDescription>Based on your assessment results</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                {topCategories.map((category, index) => (
                  <div key={category.code} className="space-y-2">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <div 
                          className="w-8 h-8 rounded-lg flex items-center justify-center"
                          style={{ backgroundColor: `${category.color}20`, color: category.color }}
                        >
                          {category.icon}
                        </div>
                        <div>
                          <span className="font-medium">{category.name}</span>
                          <Badge variant="secondary" className="ml-2">
                            #{index + 1}
                          </Badge>
                        </div>
                      </div>
                      <span className="text-sm font-medium">{category.score}%</span>
                    </div>
                    <Progress value={category.score} className="h-2" />
                  </div>
                ))}
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <TabsContent value="categories" className="space-y-4">
          <div className="grid gap-4">
            {riasecData.map((category) => (
              <Card 
                key={category.code} 
                className={`cursor-pointer transition-all hover:shadow-md ${
                  selectedCategory === category.code ? 'ring-2 ring-primary' : ''
                }`}
                onClick={() => setSelectedCategory(selectedCategory === category.code ? null : category.code)}
              >
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div 
                        className="w-12 h-12 rounded-lg flex items-center justify-center"
                        style={{ backgroundColor: `${category.color}20`, color: category.color }}
                      >
                        {category.icon}
                      </div>
                      <div>
                        <CardTitle className="text-lg">{category.name} ({category.code})</CardTitle>
                        <CardDescription>{category.description}</CardDescription>
                      </div>
                    </div>
                    <div className="flex items-center gap-3">
                      <div className="text-right">
                        <div className="text-2xl font-bold" style={{ color: category.color }}>
                          {category.score}%
                        </div>
                        <div className="text-sm text-muted-foreground">Interest Level</div>
                      </div>
                      <ChevronRight className="w-5 h-5 text-muted-foreground" />
                    </div>
                  </div>
                </CardHeader>
                
                {selectedCategory === category.code && (
                  <CardContent className="pt-0">
                    <div className="grid md:grid-cols-2 gap-4 mt-4">
                      <div>
                        <h4 className="font-medium mb-2">Related Careers</h4>
                        <div className="space-y-1">
                          {category.careers.map(career => (
                            <Badge key={career} variant="outline" className="mr-1 mb-1">
                              {career}
                            </Badge>
                          ))}
                        </div>
                      </div>
                      <div>
                        <h4 className="font-medium mb-2">Learning Resources</h4>
                        <div className="space-y-1">
                          {category.learningResources.map(resource => (
                            <Badge key={resource} variant="secondary" className="mr-1 mb-1">
                              {resource}
                            </Badge>
                          ))}
                        </div>
                      </div>
                    </div>
                  </CardContent>
                )}
              </Card>
            ))}
          </div>
        </TabsContent>

        <TabsContent value="careers" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Recommended Career Paths</CardTitle>
              <CardDescription>
                Career suggestions based on your top interest categories
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid gap-3">
                {getRecommendedCareers().map((item, index) => (
                  <div key={index} className="flex items-center justify-between p-3 border rounded-lg hover:bg-accent/50 transition-colors">
                    <div className="flex items-center gap-3">
                      <div 
                        className="w-2 h-8 rounded-full"
                        style={{ backgroundColor: item.color }}
                      />
                      <div>
                        <div className="font-medium">{item.career}</div>
                        <div className="text-sm text-muted-foreground">{item.category} Interest</div>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <Badge variant="secondary">{item.match}% Match</Badge>
                      <Button variant="ghost" size="sm">
                        Learn More
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="resources" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Personalized Learning Resources</CardTitle>
              <CardDescription>
                Curated learning materials aligned with your interests
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid gap-3">
                {getRecommendedResources().map((item, index) => (
                  <div key={index} className="flex items-center justify-between p-3 border rounded-lg hover:bg-accent/50 transition-colors">
                    <div className="flex items-center gap-3">
                      <div 
                        className="w-2 h-8 rounded-full"
                        style={{ backgroundColor: item.color }}
                      />
                      <div>
                        <div className="font-medium">{item.resource}</div>
                        <div className="text-sm text-muted-foreground">
                          Recommended for {item.category} interests
                        </div>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="flex items-center gap-1">
                        <Star className="w-4 h-4 fill-yellow-400 text-yellow-400" />
                        <span className="text-sm">{(item.relevance / 20).toFixed(1)}</span>
                      </div>
                      <Button variant="ghost" size="sm">
                        Access
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
